<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期范围">
        <el-date-picker v-model="queryParams.dateRange" type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
          class="small-date-picker" />
      </el-form-item>
      <el-form-item label="渠道编号" prop="channelCode">
        <el-input v-model="queryParams.channelCode" placeholder="请输入渠道编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="渠道名称" prop="channelName" class="single-line-label">
        <span class="label-spacing"></span>
        <el-select v-readonlyRemove v-model="selectedChannelNames" multiple clearable placeholder="请选择渠道名称" filterable
          @change="updateChannelNames">
          <el-option v-for="(item, i) in extData.channelNameList || []" :key="i" :label="item.key"
            :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="注册应用" prop="appName">
        <el-select v-model="queryParams.appName" clearable placeholder="请选择注册应用">
          <el-option v-for="(item, i) in extData.appInfoList || []" :key="i" :label="item.key" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道商务" prop="ownerName">
        <el-select v-model="queryParams.ownerId" clearable placeholder="请选择渠道商务" filterable>
          <el-option v-for="(item, i) in extData.ownerInfoList || []" :key="i" :label="item.nickname"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row style="margin-bottom: 5px;">
      <el-col style="display: flex; justify-content: flex-end;">
        <el-select style="width: 250px;" @change="tableShowColumnChange" v-model="tableShowColumn" multiple placeholder="请选择" size="small" collapse-tags>
          <el-option v-for="item in tableShowColumnOption" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="countInfoList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" /> -->
      <el-table-column v-if="isShowCol('dateInfo')" label="日期" align="center" fixed="left" prop="dateInfo" width="100" />
      <el-table-column v-if="isShowCol('channelCode')" label="渠道信息" fixed="left" align="center" prop="channelCode" width="170">
        <template slot-scope="scope">
          <el-link @click="openDialog(scope)" style="color: blue; cursor: pointer;">
            {{ scope.row.channelCode }} （{{ scope.row.channelName }})
          </el-link>
        </template>
      </el-table-column>
      <!-- <el-table-column label="渠道名称" align="center" prop="channelName" /> -->
      <!-- <el-table-column label="渠道价格（比率）" align="center" prop="channelRate" /> -->
      <el-table-column v-if="isShowCol('channelRate')" label="渠道价格（比率）" align="center">
        <template slot-scope="scope">
          {{ scope.row.priceAmount }}<br> 【 {{ scope.row.channelRate }} 】
        </template>
      </el-table-column>

      <!-- <el-table-column label="渠道价格" align="center" prop="priceAmount" /> -->
      <!-- <el-table-column label="uv数" align="center" prop="uvCount" /> -->
      <el-table-column v-if="isShowCol('pvCount')" label="pv数" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="ToUvInfo2(scope.row.channelCode, scope.row.dateInfo)">
            {{ scope.row.pvCount }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="isShowCol('uvCount')" label="uv数" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="ToUvInfo(scope.row.channelCode, scope.row.dateInfo)">
            {{ scope.row.uvCount }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('uvCost')" label="uv成本 " align="center" prop="uvCost" />
      <el-table-column v-if="isShowCol('appletCount')" label="小程序启动量 " align="center" prop="appletCount" />
      <el-table-column v-if="isShowCol('gzhCount')" label="二维码打开量 " align="center" prop="gzhCount">
        <template slot-scope="scope">
          <el-button type="text" @click="ToWxInfo(scope.row.channelCode, 'open', scope.row.appName)">
            {{ scope.row.gzhCount }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="isShowCol('erCount')" label="二维码长按量 " align="center" prop="erCount">
        <template slot-scope="scope">
          <el-button type="text" @click="ToWxInfo(scope.row.channelCode, 'er', scope.row.appName)">
            {{ scope.row.erCount }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('qrcodeOpenRate')" label="二维码打开率" align="center" width="90">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{ row.regCount ? ((row.gzhCount / row.regCount) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('qrcodePressRate')" label="二维码长按率 " align="center" width="90">
        <template slot-scope="{ row }">
          <span style="color: red">{{ row.erCount ? ((row.erCount / row.gzhCount) * 100).toFixed(2) + '%' : '0%'
          }}</span>
        </template>
      </el-table-column>


      <el-table-column v-if="isShowCol('regCount')" label="注册数（结算）" align="center" prop="regCount">
        <template slot-scope="scope">
          {{ scope.row.regCount }}（{{ scope.row.regRealCount }}）
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('zhucelv')" label="注册率" align="center" prop="zhucelv">
        <template slot-scope="{ row }">
          <span style="color: red">{{ row.zhucelv }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isShowCol('regCost')" label="注册成本" align="center" prop="regCost" />
      <el-table-column v-if="isShowCol('jjcb')" label="表单成本" align="center" prop="jjcb" />


      <!--
      <el-table-column label="进件成本" align="center" width="121">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{ row.merchPushCount && row.merchPushCount !== 0 ? ((Number(row.uvCost) /
              Number(row.merchPushCount)).toFixed(2)) : '0.00' }}
          </span>
        </template>
      </el-table-column> -->

      <el-table-column v-if="isShowCol('wechatRegCount')" label="微信量/QQ量" align="center" prop="wechatRegCount">
        <template slot-scope="scope">
          {{ scope.row.wechatRegCount }} / {{ scope.row.qqRegCount }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="QQ量" align="center" prop="qqRegCount" /> -->
      <el-table-column v-if="isShowCol('loginCount')" label="登陆量" align="center" prop="loginCount" />

      <!--      <el-table-column label="实名认证量" align="center" prop="authCount" />-->

      <el-table-column v-if="isShowCol('sourceCount')" label="资质认证量/率" align="center" width="120">
        <template slot-scope="{ row }">
          {{ row.sourceCount }} / <span style="color: red">{{ row.zizhilv }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('sourceFineCount')" label="优质用户量/率" align="center" width="120">
        <template slot-scope="{ row }">
          {{ row.sourceFineCount }} / <span style="color: red">{{ row.yzlv }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="产品列表" align="center" prop="uvProdList" />
      <el-table-column label="产品点击" align="center" prop="uvProdCount" /> -->
      <el-table-column v-if="isShowCol('uvProdCount')" label="产品uv" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showUvInfoDialog(scope.row.channelCode, queryParams.dateRange)">
            {{ scope.row.uvProdCount }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('uvConversionRate')" label="uv转化率" align="center" width="90">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{ row.regCount ? ((row.uvProdCount / row.regCount) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('uvProdProfit')" label="产品收益" align="center" prop="uvProdProfit" />

      <el-table-column v-if="isShowCol('matchSuccessCount')" label="撞库成功数/机构数" align="center" prop="wechatRegCount">
        <template slot-scope="scope">
          {{ scope.row.matchSuccessCount }} / {{ scope.row.matchSuccessNumber }}
        </template>
      </el-table-column>


      <el-table-column v-if="isShowCol('matchSuccessRate')" label="撞库成功率/多推" align="center" width="150">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{
              row.sourceCount && !isNaN(row.matchSuccessCount) && !isNaN(row.sourceCount)
                ? ((row.matchSuccessCount / row.sourceCount) * 100).toFixed(2) + '%'
                : '0%'
            }}
          </span>
          /
          <span style="color: red">
            {{
              row.sourceCount && !isNaN(row.matchSuccessNumber) && !isNaN(row.sourceCount)
                ? ((row.matchSuccessNumber / row.sourceCount) * 100).toFixed(2) + '%'
                : '0%'
            }}
          </span>
        </template>
      </el-table-column>


      <!-- <el-table-column label="授权量/率" align="center" width="121">
        <template slot-scope="{ row }">
          {{ row.approvePushNumber }} /
          <span style="color: red">
            {{ row.sourceCount ? ((row.approvePushNumber / row.sourceCount) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column> -->



      <!-- <el-table-column label="授权转化率" align="center" width="90">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{ row.merchRealPushCount ? ((row.merchPushCount / row.merchRealPushCount) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column> -->


      <el-table-column v-if="isShowCol('pushCount')" label="推送数/推送率" align="center" width="120">
        <template slot-scope="{ row }">
          {{ row.pushCount }} /
          <span style="color: red">
            {{ row.matchSuccessNumber ? ((row.pushCount / row.matchSuccessNumber) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column>


      <el-table-column v-if="isShowCol('merchPushCount')" label="推送成功数/率" align="center" width="120">
        <template slot-scope="{ row }">
          {{ row.merchPushCount }} / <span style="color: red">
            {{ row.pushCount ? ((row.merchPushCount / row.pushCount) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('wuYongValue')" label="无效用户/率" align="center" width="120">
        <template slot-scope="{ row }">
          {{ row.wuYongValue || 0 }} / <span style="color: red">
            {{ row.sourceCount ? ((row.wuYongValue || 0) / row.sourceCount * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column>


      <!-- <el-table-column label="授权成功率" align="center" width="120">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{ row.approvePushNumber ? ((row.merchPushCount / row.approvePushNumber) * 100).toFixed(2) + '%' : '0%' }}
          </span>
        </template>
      </el-table-column> -->


      <!--
      <el-table-column label="消耗均价" align="center" width="121">
        <template slot-scope="{ row }">
          <span style="color: red">
            {{ row.merchPushCount && row.merchPushCount !== 0 ? ((Number(row.merchPushAmount) /
              Number(row.merchPushCount)).toFixed(2)) : '0.00' }}
          </span>
        </template>
      </el-table-column> -->
      <el-table-column v-if="isShowCol('merchJiGouPushAmount')" label="机构收益" align="center" prop="merchJiGouPushAmount" />

      <el-table-column v-if="isShowCol('platformProfit')" label="平台收益" align="center">
        <template slot-scope="scope">
          {{ scope.row.merchPushAmount - scope.row.merchJiGouPushAmount }}
        </template>
      </el-table-column>



      <el-table-column v-if="isShowCol('merchPushAmount')" label="推送总收益" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="ToUvInfo1(scope.row.channelCode, scope.row.channelName, scope.row.dateInfo)">
            {{ scope.row.merchPushAmount }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('uvRoi')" label="uvROI" align="center" prop="uvRoi">
        <template slot-scope="{ row }">
          <span style="color: red">{{ row.uvRoi }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isShowCol('pushRoi')" label="推送ROI" align="center" prop="pushRoi">
        <template slot-scope="{ row }">
          <span style="color: red">{{ row.pushRoi }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isShowCol('totalRoi')" label="总ROI" align="center" prop="pushRoi">
        <template slot-scope="{ row }">
          <span style="color: red">{{ sumROI([row.uvRoi, row.pushRoi]) }}%</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isShowCol('ownerName')" label="商务姓名" align="center" prop="ownerName" width="100">
        <template slot-scope="scope">
          {{ scope.row.ownerName }} [{{ scope.row.ownerId }}]
        </template>
      </el-table-column>

      <el-table-column v-if="isShowCol('operate')" label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['channel:countInfo:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>



    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />



    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="渠道名称" prop="channelName">
          <el-input v-model="form.channelName" disabled />
        </el-form-item>
        <el-form-item label="日期" prop="dateInfo">
          <el-input v-model="form.dateInfo" disabled />
        </el-form-item>
        <el-form-item label="uv成本" prop="uvCost">
          <el-input v-model="form.uvCost" placeholder="请输入uv成本" />
        </el-form-item>
        <el-form-item label="uv数量" prop="uvCount">
          <el-input v-model="form.uvCount" placeholder="请输入uv数量" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :visible.sync="dialogVisible" :fullscreen="isMobileScreen"
      :title="selectedChannelCode + '(' + selectedChannelName + ')' + ' -- ' + selectedDateInfo" width="900px"
      height="500px">
      <el-row :gutter="0">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card style="max-width: 1200px;">
            <div slot="header">
              认证信息
            </div>
            <Shiming ref="ShimingRef" />
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card>
            <div slot="header">
              芝麻信息
            </div>
            <ZhiMa ref="ZhiMaRef" />
          </el-card>
        </el-col>
      </el-row>


      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card style="max-width: 1200px;">
            <div slot="header">
              年龄信息
            </div>
            <Age ref="AgeRef" />
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card style="max-width: 1200px;">
            <div slot="header">
              省份信息(前六)
            </div>
            <City ref="CityRef" />
          </el-card>
        </el-col>

      </el-row>
    </el-dialog>


    <el-dialog :visible="uvInfoDialogVisible" @close="uvInfoDialogVisible = false" title="产品UV统计：" width="50%">

      <table class="uv-table">
        <thead>
          <tr>
            <th>产品信息</th>
            <th>UV数量</th>
            <th>联登数量</th>
            <th>日期</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in (uvInfoData || [])" :key="item.id">
            <td>{{ item.idAndName }}</td>
            <td>{{ item.total }}</td>
            <td>{{ item.successUvNumber }}</td>
            <td>{{ item.dateInfo }}</td>
          </tr>
        </tbody>
      </table>

    </el-dialog>





  </div>
</template>




<script>
import { listCountInfo, getCountInfo, delCountInfo, addCountInfo, updateCountInfo } from "@/api/channel/countInfo";
import { listProfitCount } from "@/api/product/profitUvInfo";
import { listBaseInfo, baseInfoExtData, } from "@/api/channel/baseInfo";
import Shiming from './echarts/shiming.vue'
import ZhiMa from './echarts/zhima.vue'
import Age from './echarts/age.vue'
import City from './echarts/city.vue'
import dayjs from "dayjs";
import { getCount } from "@/api/channel/countInfo";

export default {
  name: "CountInfo",
  computed: {
    isMobileScreen() {
      return window.innerWidth <= 768;
    }
  },
  components: {
    Shiming,
    ZhiMa,
    City,
    Age
  },
  data() {
    return {
      tableShowColumn: [],
      tableShowColumnOption: [
        { value: 'dateInfo', label: '日期' },
        { value: 'channelCode', label: '渠道信息' },
        { value: 'channelRate', label: '渠道价格（比率）' },
        { value: 'pvCount', label: 'pv数' },
        { value: 'uvCount', label: 'uv数' },
        { value: 'uvCost', label: 'uv成本' },
        { value: 'appletCount', label: '小程序启动量' },
        { value: 'gzhCount', label: '二维码打开量' },
        { value: 'erCount', label: '二维码长按量' },
        { value: 'qrcodeOpenRate', label: '二维码打开率' },
        { value: 'qrcodePressRate', label: '二维码长按率' },
        { value: 'regCount', label: '注册数（结算）' },
        { value: 'zhucelv', label: '注册率' },
        { value: 'regCost', label: '注册成本' },
        { value: 'jjcb', label: '表单成本' },
        { value: 'wechatRegCount', label: '微信量/QQ量' },
        { value: 'loginCount', label: '登陆量' },
        { value: 'sourceCount', label: '资质认证量/率' },
        { value: 'sourceFineCount', label: '优质用户量/率' },
        { value: 'uvProdCount', label: '产品uv' },
        { value: 'uvConversionRate', label: 'uv转化率' },
        { value: 'uvProdProfit', label: '产品收益' },
        { value: 'matchSuccessCount', label: '撞库成功数/机构数' },
        { value: 'matchSuccessRate', label: '撞库成功率/多推' },
        { value: 'pushCount', label: '推送数/推送率' },
        { value: 'merchPushCount', label: '推送成功数/率' },
        { value: 'wuYongValue', label: '无效用户/率' },
        { value: 'merchJiGouPushAmount', label: '机构收益' },
        { value: 'platformProfit', label: '平台收益' },
        { value: 'merchPushAmount', label: '推送总收益' },
        { value: 'uvRoi', label: 'uvROI' },
        { value: 'pushRoi', label: '推送ROI' },
        { value: 'totalRoi', label: '总ROI' },
        { value: 'ownerName', label: '商务姓名' },
        { value: 'operate', label: '操作' }
      ],
      realNameRateData: null,
      myChart: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 渠道统计信息表格数据
      countInfoList: [],
      allUvCount: [],
      allPvCount: [],
      baseInfoList: [],
      selectedChannelNames: [],
      uvInfoData: [],
      extData: {},
      channelData: {},
      UvCount: {},
      pvCount: {},
      ownerInfoList: [],
      dialogVisible: false,
      uvInfoDialogVisible: false,
      selectedChannelCode: '',
      selectedChannelName: '',
      selectedDateInfo: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      rules: {
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateInfo: null,
        channelCode: null,
        channelName: null,
        channelRate: null,
        priceAmount: null,
        uvCount: null,
        pvCount: null,
        uvCost: null,
        appletCount: null,
        gzhCount: null,
        erCount: null,
        comCount: null,
        wxComCount: null,
        regCount: null,
        regCost: null,
        wechatRegCount: null,
        qqRegCount: null,
        loginCount: null,
        authCount: null,
        sourceCount: null,
        uvProdList: null,
        uvProdCount: null,
        uvProdProfit: null,
        merchPushCount: null,
        merchPushAmount: null,
        ownerId: null,
        ownerName: null,
        startDateInfo: null,
        endDateInfo: null,
        dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
      },
      form: {},
    };
  },
  created() {
    this.initCol();
    this.getList();
    const thirtySeconds = 60 * 1000; // 60秒的毫秒数
    setInterval(() => {
      this.getList();
    }, thirtySeconds);
    this.getOptions();
    this.initData();
  },
  methods: {
    initCol(){
      const lTableShowColumn = localStorage.getItem('tableShowColumn');
      if(lTableShowColumn){
        console.log(lTableShowColumn.split(','))
        this.tableShowColumn = lTableShowColumn.split(',')
      }else{
        this.tableShowColumn = this.tableShowColumnOption.map((item) => item.value);
        localStorage.setItem('tableShowColumn', this.tableShowColumn)
      }
    },
    isShowCol(col){
      return this.tableShowColumn.includes(col);
    },
    tableShowColumnChange(){
      localStorage.setItem('tableShowColumn', this.tableShowColumn)
    },
    sumROI(roiList = []) {
      const sum = roiList.reduce((curr, item) => {
        return curr + parseFloat(item) * 100
      }, 0)
      return sum / 100
    },
    showUvInfoDialog(channelCode, dateRange) {
      listProfitCount({ channelCode, startDateInfo: dayjs(dateRange[0]).format('YYYY-MM-DD'), endDateInfo: dayjs(dateRange[1]).format('YYYY-MM-DD') }).then(response => {
        this.uvInfoData = response.rows;
        this.uvInfoDialogVisible = true;
      });
    },
    updateChannelNames() {
      this.queryParams.channelName = this.selectedChannelNames.join(',');
    },

    ToWxInfo(channelCode, type = 'all', appName) {
      console.log()
      this.$router.push({
        path: '/channel/countWxInfo', query: {
          channelCode: channelCode,
          appName: this.queryParams.appName,
          // startDateInfo: this.queryParams.dateRange[0],
          // endDateInfo: this.queryParams.dateRange[1],
          type
        }
      })
    },
    ToUvInfo(channelCode, dateInfo) {
      this.$router.push({ path: '/channel/countUvInfo', query: { channelCode: channelCode, dateInfo: dateInfo } })
    },
    ToUvInfo1(channelCode, channelName, dateInfo) {
      this.$router.push({ path: '/channel/pushdata', query: { channelCode: channelCode, channelName: channelName, dateInfo: dateInfo } })
    },
    ToUvInfo2(channelCode, dateInfo) {
      this.$router.push({ path: '/channel/countPvInfo', query: { channelCode: channelCode, dateInfo: dateInfo } })
    },
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },

    openDialog(scope) {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');

      const startDate = `${year}-${month}-${day}`;
      const endDateInfo = `${year}-${month}-${day}`;

      const channelName = scope.row.channelName || this.queryParams.channelName || '';
      const channelCode = scope.row.channelCode || this.queryParams.channelCode || '';

      let channelData = {
        channelCode: scope.row.channelCode,
        channelName: channelName,
        dateInfo: scope.row.dateInfo || '',
      };


      if (!scope.row.dateInfo) {
        channelData.startDateInfo = startDate;
        channelData.endDateInfo = endDateInfo;
      }

      this.selectedChannelCode = channelCode;
      this.selectedChannelName = channelName;
      this.selectedDateInfo = scope.row.dateInfo || (startDate + '--' + endDateInfo);


      this.dialogVisible = true;
      this.$nextTick(async () => {
        const response = await getCount(channelData)
        const { ageMemberData, authMemberData, zhiMaMemberData, provinceMemberData } = response.data;
        this.$refs.ShimingRef.rederData(authMemberData);
        this.$refs.ZhiMaRef.rederData(zhiMaMemberData);
        this.$refs.AgeRef.rederData(ageMemberData);
        this.$refs.CityRef.rederData(provinceMemberData);
      });
    },


    getList() {
      this.loading = true;
      const sata = { ...this.queryParams };
      if (sata.dateRange && sata.dateRange.length === 2) {
        const startDate = this.queryParams.dateRange[0];
        const endDateInfo = this.queryParams.dateRange[1];
        sata.startDateInfo = startDate;
        sata.endDateInfo = endDateInfo;
      }
      delete sata.dateRange;
      listCountInfo(sata).then(response => {

        this.countInfoList = response.rows.slice((this.queryParams.pageNum - 1) * this.queryParams.pageSize, this.queryParams.pageNum * this.queryParams.pageSize);
        // this.countInfoList = response.rows;
        // console.log(this.countInfoList);
        this.total = response.total;
        this.loading = false;
      });
    },

    /**渠道  下拉框搜索*/
    async initData() {
      const response = await listBaseInfo()
      this.baseInfoList = response.rows;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dateInfo: null,
        channelCode: null,
        channelName: null,
        channelRate: null,
        priceAmount: null,
        uvCount: null,
        uvCost: null,
        appletCount: null,
        gzhCount: null,
        erCount: null,
        regCount: null,
        regCost: null,
        wechatRegCount: null,
        qqRegCount: null,
        loginCount: null,
        authCount: null,
        sourceCount: null,
        uvProdList: null,
        uvProdCount: null,
        uvProdProfit: null,
        merchPushCount: null,
        merchPushAmount: null,
        ownerId: null,
        ownerName: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.dateRange = [];
      this.queryParams.ownerId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加渠道统计信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCountInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改渠道统计信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCountInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCountInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除渠道统计信息编号为"' + ids + '"的数据项？').then(function () {
        return delCountInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('channel/countInfo/export', {
        ...this.queryParams
      }, `countInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.uv-table {
  width: 100%;
  border-collapse: collapse;
}

.uv-table th,
.uv-table td {
  border: 1px solid #e0e0e0;
  padding: 8px;
  text-align: center;
}

.uv-table th {
  background-color: #f5f5f5;
}

.table-card {
  padding: 20px;
}
</style>
